//
//  ViewController.m
//  TencentDistrictSearch
//
//  Created by v_hefang on 2020/9/8.
//  Copyright © 2020 v_hefang. All rights reserved.
//

#import "ViewController.h"
#import <QMapKit/QMapKit.h>
#import <QMapKit/QMSSearchKit.h>
#import "ProvinceModel.h"
#import "CityModel.h"
#import "DistrictModel.h"


@interface ViewController () <QMapViewDelegate, QMSSearchDelegate, UIPickerViewDelegate, UIPickerViewDataSource>

@property (nonatomic, strong) QMapView *mapView;
@property (nonatomic, strong) QMSSearcher *searcher;

@property (nonatomic, strong) NSMutableArray *provinceModelArray;
@property (nonatomic, strong) UIPickerView *pickerView;
@property (nonatomic, strong) ProvinceModel *selectProvinceModel;
@property (nonatomic, strong) CityModel *selectCityModel;
@property (nonatomic, strong) DistrictModel *selectDistrictModel;

@end

@implementation ViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    
    self.navigationItem.rightBarButtonItem = [[UIBarButtonItem alloc] initWithTitle:@"Picker" style:UIBarButtonItemStylePlain target:self action:@selector(showPicker)];
    
    [self setupMapView];
    [self setupSearcher];
}

- (void)showPicker {
    if (_provinceModelArray.count == 0) {
        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:@"加载中" message:@"行政区划信息没有加载结束, 请稍后再试!" preferredStyle:UIAlertControllerStyleAlert];
        [self presentViewController:alertController animated:YES completion:nil];
        
        UIAlertAction *action = [UIAlertAction actionWithTitle:@"确定" style:UIAlertActionStyleCancel handler:^(UIAlertAction * _Nonnull action) {
            [alertController dismissViewControllerAnimated:YES completion:nil];
        }];
        [alertController addAction:action];
        return;
    }
    self.pickerView.hidden = !self.pickerView.hidden;
}


#pragma mark - MapView
- (void)setupMapView {
    
    CGFloat height = self.view.bounds.size.height - self.navigationController.navigationBar.bounds.size.height - [UIApplication sharedApplication].statusBarFrame.size.height;
    
    self.mapView = [[QMapView alloc] initWithFrame:CGRectMake(0, self.view.bounds.size.height - height, self.view.bounds.size.width, height)];
    self.mapView.delegate = self;
    [self.view addSubview:self.mapView];
    
    [self.mapView setCenterCoordinate:CLLocationCoordinate2DMake(40.040219,116.273348)];
}


#pragma mark - Searcher
- (void)setupSearcher {
    _searcher = [[QMSSearcher alloc] initWithDelegate:self];
    QMSDistrictListSearchOption *option = [[QMSDistrictListSearchOption alloc] init];
    [_searcher searchWithDistrictListSearchOption:option];
}

- (void)searchWithDistrictSearchOption:(QMSDistrictBaseSearchOption *)districtSearchOption didRecevieResult:(QMSDistrictSearchResult *)districtSearchResult {
    
    _provinceModelArray = [NSMutableArray array];
    
    NSArray *provinceArray = districtSearchResult.result[0];
    NSArray *cityArray = districtSearchResult.result[1];
    NSArray *districtArray = districtSearchResult.result[2];
    
    for (QMSDistrictData *provinceData in provinceArray) {
        ProvinceModel *provinceModel = [ProvinceModel provinceWithDistrictData:provinceData];
        
        // 取出市级
        NSMutableArray *cityModelArray = [NSMutableArray array];
        NSArray<NSNumber *> *cidx = provinceData.cidx;
        QMSDistrictData *cityData = cityArray[cidx.firstObject.intValue];
        
        // 判断二级结构后面是否还有三级结构
        // 如果没有, 则直接使用一级结构作为二级结构, 二级结构作为三级结构, 如: 北京-北京-东城区
        if (cityData.cidx == nil) {
            CityModel *cityModel = [CityModel cityWithDistrictData:provinceData];
            [cityModelArray addObject:cityModel];
            
            // 设置三级结构
            NSMutableArray *districtModelArray = [NSMutableArray array];
            int firstIndex = provinceData.cidx.firstObject.intValue;
            int lastIndex = provinceData.cidx.lastObject.intValue;
            
            // 将二级结构设置为三级结构
            for (int i = firstIndex; i < lastIndex + 1; i++) {
                QMSDistrictData *districData = cityArray[i];
                DistrictModel *districtModel = [DistrictModel districtWithDistrictData:districData];
                [districtModelArray addObject:districtModel];
            }
            
            cityModel.districts = districtModelArray;
            provinceModel.cities = cityModelArray;
        } else {
            // 填充二级结构
            int cityFirstIndex = provinceData.cidx.firstObject.intValue;
            int cityLastIndex = provinceData.cidx.lastObject.intValue;
            
            for (int i = cityFirstIndex; i < cityLastIndex + 1; i++) {
                QMSDistrictData *cityData = cityArray[i];
                CityModel *cityModel = [CityModel cityWithDistrictData:cityData];
                [cityModelArray addObject:cityModel];
                
                // 设置三级结构
                int districtFirstIndex = cityData.cidx.firstObject.intValue;
                int districtLastIndex = cityData.cidx.lastObject.intValue;
                NSMutableArray *districtModelArray = [NSMutableArray array];
                
                for (int i = districtFirstIndex; i < districtLastIndex + 1; i++) {
                    QMSDistrictData *districtData = districtArray[i];
                    DistrictModel *districtModel = [DistrictModel districtWithDistrictData:districtData];
                    [districtModelArray addObject:districtModel];
                }
                
                cityModel.districts = districtModelArray;
            }
            
            provinceModel.cities = cityModelArray;
        }
        
        [_provinceModelArray addObject:provinceModel];
    }
    
    _selectProvinceModel = _provinceModelArray[0];
    _selectCityModel = _selectProvinceModel.cities[0];
    _selectDistrictModel = _selectCityModel.districts[0];
    
    [self setupPickerView];
}


#pragma mark - PickerView
- (void)setupPickerView {
    _pickerView = [[UIPickerView alloc] initWithFrame:self.mapView.bounds];
    _pickerView.delegate = self;
    _pickerView.dataSource = self;
    _pickerView.hidden = YES;
    _pickerView.backgroundColor = [UIColor colorWithRed:1 green:1 blue:1 alpha:0.8];
    
    [self.mapView addSubview:_pickerView];
}

- (NSInteger)numberOfComponentsInPickerView:(UIPickerView *)pickerView {
    return 3;
}

- (NSInteger)pickerView:(UIPickerView *)pickerView numberOfRowsInComponent:(NSInteger)component {
    
    if (component == 0) {
        return self.provinceModelArray.count;
    } else if (component == 1) {
        // 默认选择第0个
        return _selectProvinceModel.cities.count;
    } else {
        return _selectCityModel.districts.count;
    }
    
    return 0;
}

- (NSString *)pickerView:(UIPickerView *)pickerView titleForRow:(NSInteger)row forComponent:(NSInteger)component {
    if (component == 0) {
        ProvinceModel *pModel = self.provinceModelArray[row];
        return pModel.fullname;
    } else if (component == 1) {
        CityModel *cModel = _selectProvinceModel.cities[row];
        return cModel.fullname;
    } else {
        DistrictModel *dModel = _selectCityModel.districts[row];
        return dModel.fullname;
    }
}

- (void)pickerView:(UIPickerView *)pickerView didSelectRow:(NSInteger)row inComponent:(NSInteger)component {
    if (component == 0) {
        _selectProvinceModel = self.provinceModelArray[row];
        _selectCityModel = _selectProvinceModel.cities[0];
        // 刷新后两个
        [pickerView reloadComponent:1];
        [pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:1 animated:NO];
        [pickerView selectRow:0 inComponent:2 animated:NO];
    } else if (component == 1) {
        _selectCityModel = _selectProvinceModel.cities[row];
        // 刷新最后一个
        [_pickerView reloadComponent:2];
        [pickerView selectRow:0 inComponent:2 animated:NO];
    }
}

@end
